//#define __DEBUG__
#define THIS_FILE "fn_checknew.sqf"
#include "x_setup.sqf"

private ["_newUnits", "_newVehicles", "_nn", "_fh", "_iswu", "_gg", "_m", "_markstr", "_unknownstr", "_OriginalSide", "_s", "_cameras", "_nunits"];
_markstr = _this select 0;
_unknownstr = _this select 1;
_cameras = _this select 2;
_allUnits = if (isNil "d_init_started") then {allUnits} else {if (isMultiplayer) then {(playableUnits - [objNull])} else {switchableUnits}};
_newUnits = _allUnits - KEGs_deathCam;
_newVehicles = vehicles - KEGs_ehVehicles;
if (count _newVehicles > 0) then {
	KEGs_ehVehicles = [KEGs_ehVehicles, _newVehicles] call KEGs_fnc_arrayPushStack;
	{
		_nn = _x getVariable "KEGs_EHFired";
		if (isNil "_nn") then {
			_fh = _x addEventHandler ["fired", {["UnitFired",_this] call KEGs_fnc_spectate_events}];
			_x setVariable ["KEGs_EHFired", _fh];
			_x setVariable ["KEGs_mapmove", false];
		};
	} foreach _newVehicles;
};
if (count _newUnits > 0) then {
	_nunits = [];
	{
		_iswu = false;
		_gg = _x getVariable "KEGs_SPECT";
		if (isNil "_gg" || {!_gg}) then {
			_x setVariable ["KEGs_SPECT", true];
			_x setVariable ["KEGs_mapmove", false];
			_iswu = true;
		};
		if (!isMultiplayer && {KEGs_UseLog}) then {
			_nn = _x getVariable "KEGs_EHKilled";
			if (isNil "_nn") then {
				_fh = _x addEventHandler ["killed", {["UnitKilled",_this] call KEGs_fnc_spectate_events}];
				_x setVariable ["KEGs_EHKilled", _fh];
			};
		};
		if (!_iswu) then {
			_nunits set [count _nunits, _x];
			_m = createMarkerLocal [format[_markstr, count KEGs_markers], [0, 0, 0]];
			_m setMarkerTypeLocal "hd_dot";
			_m setMarkerSizeLocal [0.4, 0.4];
			_nn = if (alive _x) then {name _x} else {_unknownstr};
			KEGs_markers set [count KEGs_markers, [_m, _x, _nn]];

			_OriginalSide = _x call KEGs_fnc_CheckOriginalSide;
			KEGs_sidecache set [count KEGs_sidecache, _OriginalSide];

			_m setMarkerColorLocal (_OriginalSide call KEGs_fnc_GetMCol);
			_m setMarkerPosLocal (visiblePositionASL  (vehicle _x));

			_s = "#particlesource" createVehicleLocal getPosASL _x;
			KEGs_Tagsources set [count KEGs_Tagsources, [_x, _s]];

			if (KEGs_Tags == 1) then {
				["ToggleTags", [false, _cameras select KEGs_cameraIdx]] call KEGs_fnc_spectate_events;
				["ToggleTags", [true, _cameras select KEGs_cameraIdx]] call KEGs_fnc_spectate_events;
			};
			KEGs_namecache set [count KEGs_namecache, _nn];
		};
	} forEach _newUnits;

	KEGs_deathCam = [KEGs_deathCam, _nunits] call KEGs_fnc_arrayPushStack;				

	KEGs_NeedUpdateLB = true;
};
KEGs_lastCheckNewUnits = time;
KEGs_newCheckUn = false;